<template>
	<div class="carManager">
		<div class="crumbs">
			<el-breadcrumb separator="/">
				<el-breadcrumb-item>
					<i class="el-icon-lx-cascades"></i>
					设备管理
				</el-breadcrumb-item>
			</el-breadcrumb>
		</div>
		<div class="container">
			<div class="handle-box">
				<el-select v-model="idDev" placeholder="类别查询" @change='getNewData()'>
						<el-option v-for="item in type" :key="item.id" :label="item.name" :value="item.id"></el-option>
				</el-select>
			</div>
			<el-table :data="tableData" border class="table" ref="multipleTable">
				<el-table-column type="index" width="55" align="center" label="序号" class-name="table"></el-table-column>
				<el-table-column prop="deviceName" label="设备名称" width="120" class-name="table"></el-table-column>
				<el-table-column prop="agentName" label="代理商名称" width="120" class-name="table"></el-table-column>
				<el-table-column prop="deviceCode" label="设备号" width="120" class-name="table"></el-table-column>
				<el-table-column prop="staffName" label="员工" width="120" class-name="table"></el-table-column>
				<el-table-column prop="deviceState" label="状态" width="120" class-name="table"></el-table-column>
				<el-table-column prop="deviceUpdatetime" label="创建时间" class-name="table"></el-table-column>
				<el-table-column label="操作" width="220" align="center" class-name="table">
					<template slot-scope="scope">
						<el-button type="text" icon="el-icon-edit" @click="qRcode(scope.$index, scope.row)">二维码</el-button>
						<el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
						<!-- <el-button type="text" icon="el-icon-delete" class="red" @click="handleDelete(scope.$index, scope.row)">删除</el-button> -->
					</template>
				</el-table-column>
			</el-table>
			<div class="pagination">
				<el-pagination
					background
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
					:current-page="cur_page"
					:page-size="pagesize"
					:total="totalRecords"
					:page-sizes="[5, 10, 20, 40]"
					layout="total, sizes, prev, pager, next, jumper"
				></el-pagination>
			</div>
		</div>

		<!-- 编辑弹出框 -->
		<el-dialog title="编辑" :visible.sync="editVisible" width="30%">
			<el-form ref="editForm" :model="editForm" label-width="100px" :rules="FormRules">		
				<el-form-item label="设备名称" prop="deviceName">
					<el-input v-model="editForm.deviceName"></el-input>
				</el-form-item>
				<el-form-item label="代理商名称" prop="deviceAgentId" v-show='keyagent' >
					<el-select v-model="editForm.deviceAgentId" placeholder="选择代理商">
						<el-option v-for="item in agentNames" :key="item.agentId" :label="item.agentName" :value="item.deviceAgentId"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="员工" prop="deviceStaffId" v-show='keystaff'>
					<el-select v-model="editForm.deviceStaffId" placeholder="选择员工">
						<el-option v-for="item in staffNames" :key="item.staffId" :label="item.staffName" :value="item.deviceStaffId"></el-option>
					</el-select>
				</el-form-item>  
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="editVisible = false">取 消</el-button>
				<el-button type="primary" @click="saveEdit">确 定</el-button>
			</span>
		</el-dialog>
		<!-- 删除提示框 -->
		<el-dialog title="提示" :visible.sync="delVisible" width="300px" center>
			<div class="del-dialog-cnt">删除不可恢复，是否确定删除？</div>
			<span slot="footer" class="dialog-footer">
				<el-button @click="delVisible = false">取 消</el-button>
				<el-button type="primary" @click="deleteRow">确 定</el-button>
			</span>
		</el-dialog>
		<div class="newqrcode" v-show="key">
     <div  id="qrCode" ref="qrCodeDiv">  
		 </div>
		 <el-button style="	height: 30px;width: 100px;margin-left:30px;"  @click="dis()"  type="danger" round>关闭</el-button>
		 <el-button style="	height: 30px;width: 100px;margin-left:30px;"  @click="downs()"  type="success" round>下载</el-button>
		</div>
	</div>
</template>

<script>
import html2canvas from 'html2canvas';
import QRCode from 'qrcodejs2'
import Validator from 'async-validator';
export default {
	name: 'carManager',
	data() {
		return {
			type:[
				{
					id:0,
					name:'未分配'
				},
				{
					id:1,
					name:'正常'
				},
				{
					id:2,
					name:'异常'
				}
			],
			idDev:'',//设备选择更新id
			qrcodeName:'MT320',//设备名称
			testa :null,
			key:false,//控制二维码展示
			keyagent:true,//控制代理商展示
			keystaff:true,//控制员工显示
			agentNames: [], // 添加代理商名字下拉框
			staffNames: [], // 添加员工名字下拉框
			value: '',
			tableData: [],
			cur_page: 1,
			pagesize: 20,
			totalRecords: 0,
			totalPages: 0,
			multipleSelection: [],
			select_cate: '',
			select_word: '',
			del_list: [],
			is_search: false,
			editVisible: false,
			addVisible: false,
			delVisible: false,
			editForm: {
				deviceId: '',
				deviceName: '',
				deviceAgentId: '',
				deviceStaffId: ''
			},
			FormRules: {
        deviceAgentId: [{ message: "代理商不能为空", required: true, trigger: "blur" }],
				deviceStaffId: [{ message: "员工不能为空", required: true, trigger: "blur" }],
				deviceName:[{ message: "设备不能为空", required: true, trigger: "blur" }]
      },
			addForm: {
				deviceId: '',
				deviceName: '',
				deviceAgentId: '',
				deviceStaffId: ''
			},
			idx: -1,
			id: -1
		};
	},
	created() {
		this.getData();
		this.getAgentSelect(); //查所有代理商
		this.getStaffSelect(); //查所有员工
	},
	computed: {
		data() {
			return this.tableData.filter(d => {
				let is_del = false;
				for (let i = 0; i < this.del_list.length; i++) {
					if (d.name === this.del_list[i].name) {
						is_del = true;
						break;
					}
				}
				if (!is_del) {
					if (d.address.indexOf(this.select_cate) > -1 && (d.name.indexOf(this.select_word) > -1 || d.address.indexOf(this.select_word) > -1)) {
						return d;
					}
				}
			});
		}
	},
	methods: {
    //获取选择数据
     getNewData() {
      var res = this;
      this.$axios({
        url: "/api/waterDevice/selectDeviceByPageAndDeviceState",
        method: "post",
        data: {pageNum: res.cur_page, pageSize: res.pagesize,deviceState:res.idDev}
      })
        .then(function(response) {
          if (response.status <= 200) {
            res.tableData = response.data.data.list;
            res.totalRecords = response.data.data.total; //总条数
            console.log(response.data);
          }
        })
        .catch(function(error) {
          res.$message.error("查询失败: " + error);
          console.log(error);
        });
    },
		//二维码消失
		dis(){
           this.key=false
		},
		//二维码生成
		qRcode(index,row){
			      this.qrcodeName=row.deviceCode
            if(this.key==false){
              this.key=true
            if(this.testa!=null){//清除new的图示
              this.testa.clear()
            }else{
            this.testa = new QRCode(this.$refs.qrCodeDiv, {
                text: 'http://ly.xianmiao.shop/water/html/message.html?devcode='+row.deviceCode,
                width: 300,
                height: 300,
                colorDark: "#333333", //二维码颜色
                colorLight: "#ffffff", //二维码背景色
                correctLevel: QRCode.CorrectLevel.L//容错率，L/M/H
                   })
            }
              this.testa.clear() //清除二维码 
              this.testa.makeCode('http://ly.xianmiao.shop/water/html/message.html?devcode='+row.deviceCode) //生成另一新的二维码
            }else{
            }
		},
		//二维码下载
		 downs(){
            // //找到canvas标签
            let myCanvas = document.getElementById('qrCode').getElementsByTagName('canvas');
            let img=document.getElementById('qrCode').getElementsByTagName('img')
            // // //创建一a标签节点
            let a= document.createElement("a")
            // //设置a标签的href属性（将canvas变成png图片）
            let imgURL=myCanvas[0].toDataURL('image/jpg');
            let ua = navigator.userAgent;
            if (ua.indexOf("Trident") != -1 && ua.indexOf("Windows") != -1) { // IE内核 并且  windows系统 情况下 才执行;
                var bstr = atob(imgURL.split(',')[1])
                var n = bstr.length
                var u8arr = new Uint8Array(n)
                while (n--) {
                  u8arr[n] = bstr.charCodeAt(n)
                }
                var blob = new Blob([u8arr])
                window.navigator.msSaveOrOpenBlob(blob, this.qrcodeName + '.' + 'png')
            }else if(ua.indexOf("Firefox") > -1){ //火狐兼容下载
                let blob = this.base64ToBlob(imgURL); //new Blob([content]);
                let evt = document.createEvent("HTMLEvents");
                evt.initEvent("click", true, true);//initEvent 不加后两参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
                a.download =this.qrcodeName;//下载图片名称，如果填内容识别不到，下载为未知文件，所以我这里就不填为空
                a.href = URL.createObjectURL(blob);
                a.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true, view: window}));//兼容火狐
            }else{ //谷歌兼容下载
                img.src=myCanvas[0].toDataURL('image/jpg');
                // a.href = myCanvas[0].toDataURL('image/png').replace('image/png', 'image/octet-stream')
                a.href=img.src
                //设置下载文件的名字
                a.download = this.qrcodeName
                 //点击
                a.click()
            }
        },
        //base64转blob
        base64ToBlob(code) {
            let parts = code.split(';base64,');
            let contentType = parts[0].split(':')[1];
            let raw = window.atob(parts[1]);
            let rawLength = raw.length;
            let uInt8Array = new Uint8Array(rawLength);
            for (let i = 0; i < rawLength; ++i) {
            uInt8Array[i] = raw.charCodeAt(i);
            }
            return new Blob([uInt8Array], {type: contentType});
        },
		//每页显示数改变
		handleSizeChange(val) {
			this.pagesize = val;
			this.getData();
		},
		// 分页导航
		handleCurrentChange(val) {
			this.cur_page = val;
			this.getData();
		},
		//页面初始化时获取下拉框里面的数据 【代理商】
		getAgentSelect() {
			var res = this;
			this.$axios({
				url: '/api/waterAgent/selectWaterAgentAll',
				method: 'post',
				data: {pageNum: res.cur_page, pageSize: res.pagesize}
			})
				.then(function(response) {
					if (response.status <= 200) {
						for (var i = 0; i < response.data.data.list.length; i++) {
							res.agentNames.push({
								agentName: response.data.data.list[i].agentName,
								deviceAgentId: response.data.data.list[i].agentId
							});
						}
					}
				})
				.catch(function(error) {
					res.$message.error('查询失败: ' + error);
					console.log(error);
				});
		},
		//页面初始化时获取下拉框里面的数据 【员工】
		getStaffSelect() {
			var res = this;
			this.$axios({
				url: '/api/waterStaff/findAllStaff',
				method: 'get',
				data: {}
			})
				.then(function(response) {
					if (response.status <= 200) {
						for (var i = 0; i < response.data.length; i++) {
							res.staffNames.push({
								staffName: response.data[i].staffName,
								deviceStaffId: response.data[i].staffId
							});
						}
					}
				})
				.catch(function(error) {
					res.$message.error('查询失败: ' + error);
					console.log(error);
				});
		},
		// 获取 easy-mock 的模拟数据
		getData() {
			if(localStorage.roleType==0){
				this.keyagent=true
				this.keystaff=false
			}else if(localStorage.roleType==1){
					this.keyagent=false
				this.keystaff=true
			}
			var res = this;
			var id=localStorage.loginId
			var type=localStorage.roleType
			if(type==0){
					this.$axios({
				url: '/api/waterDevice/selectDeviceByPageAndDeviceState',
				method: 'post',
				data: { pageNum: res.cur_page, pageSize: res.pagesize }
			})
				.then(function(response) {
					if (response.status <= 200) {
						console.log(response.data)
						res.tableData = response.data.data.list;
						res.totalRecords = response.data.data.total; //总条数s
					}
				})
				.catch(function(error) {
					res.$message.error('查询失败: ' + error);
					console.log(error);
				});
			}else if(type==1){
					this.$axios({
				url: '/api/waterDevice/selectDeviceByPageAndDeviceState',
				method: 'post',
				data: { pageNum: res.cur_page, pageSize: res.pagesize,deviceAgentid:id }
			})
				.then(function(response) {
					if (response.status <= 200) {
						console.log(response.data)
						res.tableData = response.data.data.list;
						res.totalRecords = response.data.data.total; //总条数s
					}
				})
				.catch(function(error) {
					res.$message.error('查询失败: ' + error);
					console.log(error);
				});
			}else{
        this.$axios({
				url: '/api/waterDevice/selectDeviceByPageAndDeviceState',
				method: 'post',
				data: { pageNum: res.cur_page, pageSize: res.pagesize ,deviceStaffid:id}
			})
				.then(function(response) {
					if (response.status <= 200) {
						console.log(response.data)
						res.tableData = response.data.data.list;
						res.totalRecords = response.data.data.total; //总条数s
					}
				})
				.catch(function(error) {
					res.$message.error('查询失败: ' + error);
					console.log(error);
				});
			}
		},
		formatter(row, column) {
			return row.address;
		},
		filterTag(value, row) {
			return row.tag === value;
		},
		handleEdit(index, row) {
			this.idx = index;
			this.deviceId = row.wdDeviceId;
			this.editForm = {
				deviceId: row.deviceId,
				deviceName: row.deviceName,
				deviceAgentId: row.deviceAgentid,
				deviceStaffId: row.deviceStaffid,
				deviceState: row.deviceState,
				deviceCreateTime: row.deviceCreateTime
			};
			this.editVisible = true;
		},
		handleDelete(index, row) {
			this.idx = index;
			console.log(row.wdDeviceId);
			this.id = row.wdDeviceId;
			this.delVisible = true;
		},
		delAll() {
			const length = this.multipleSelection.length;
			let str = '';
			this.del_list = this.del_list.concat(this.multipleSelection);
			for (let i = 0; i < length; i++) {
				str += this.multipleSelection[i].name + ' ';
			}
			this.$message.success('删除了' + str);
			this.multipleSelection = [];
		},
		handleSelectionChange(val) {
			this.multipleSelection = val;
		},
		// 保存编辑
		saveEdit() {
			var res = this;
			var setData = this.editForm;
			console.log( setData)
			this.$refs.editForm.validate(valid => {
				if (!valid) {
					res.$message.success('格式不正确');
				} else {
					this.$axios({
						url: '/api/waterDevice/updateByPrimaryKey',
						method: 'post',
						data: setData
					})
						.then(function(response) {
							if (response.status <= 200) {
								res.editVisible = false;
								res.$message.success('修改成功');
								res.$message.success(`修改第 ${res.idx + 1} 行成功`);
								res.getData();
							}
						})
						.catch(function(error) {
							res.$message.success('修改失败！');
							console.log(error);
						});
				}

				// 验证通过后的处理...
			});
		},
		// 添加
		saveAdd() {
      //  var id = localStorage.loginId;
      var res = this;
      var setData = this.addForm;
      // setData['staffAgentId']=id
			this.$refs.addForm.validate(valid => {
				if (!valid) {
					res.$message.success('格式不正确');
				} else {
					this.$axios({
						url: '/api/waterDevice/insert',
						method: 'post',
						data: setData
					})
						.then(function(response) {
							if (response.status <= 200) {
								res.$message.success(response.data.message);
								res.addVisible = false;
								res.getData();
							}
						})
						.catch(function(error) {
							res.$message.error('添加失败！');
							console.log(error);
						});
				}
			});
		},
		// 确定删除
		deleteRow() {
			var res = this;
			console.log(this.id);
			var id = Number(res.id);
			this.$axios({
				url: "/api/waterDevice/deleteByPrimaryKey",
				method: 'post',
				data: { id: id }
			})
				.then(function(response) {
					if (response.status <= 200) {
						res.$message.success('删除成功');
						res.delVisible = false;
						res.getData()
					}
				})
				.catch(function(error) {
					res.$message.success('查询失败！');
					console.log(error);
				});
		}
	}
};
</script>

<style scoped>
 #qrCode { 
    display: inline-block;
  }
	.newqrcode{
		position: fixed;
		left: 45%;
		top:300px;
		z-index: 999;
		background: gray;
		height: 340px;
		width: 300px;
	}
#qrCode img {
      width: 132px;
      height: 132px;
      background-color: #fff; 
      padding: 6px; 
}
.huizong {
	height: 30px;
	width: 400px;
	position: relative;
}
.huizong span {
	height: 30px;
	width: 400px;
	position: absolute;
	bottom: -60px;
	z-index: 999;
}
.tianjia {
	margin-left: 10px;
}
.sousuo {
	margin-right: 10px;
}
.handle-box {
	margin-bottom: 20px;
}

.handle-select {
	width: 120px;
}

.handle-input {
	width: 300px;
	display: inline-block;
}
.del-dialog-cnt {
	font-size: 16px;
	text-align: center;
}
.table {
	width: 100%;
	font-size: 14px;
}
.red {
	color: #ff0000;
}
.mr10 {
	margin-right: 10px;
}
.outup {
	font-size: 12px;
	color: #fff;
	background-color: #409eff;
	display: inline-block;
	border-radius: 3px;
	padding: 8px 15px;
	margin-left: 10px;
	margin-top: 3px;
}
.upload-demo {
	height: 30px;
	width: 100px;
	display: inline-block;
	margin-left: 10px;
}
.inup {
	margin-top: 10px;
}
</style>
<style>
.el-upload--text {
	width: 60px;
	height: 30px;
	display: inline-block;
	border: 0;
	overflow: visible;
}
.el-table--border {
	border: 1px solid black;
}
.el-table--border,
.el-table--border th,
.el-table td,
.el-table th {
	border-right: 1px solid black;
	border-bottom-color: black;
	border-left-color: black;
}
.table {
	border-bottom-color: black !important;
	border-left-color: black !important;
}
</style>
